//数据库
const loki = require('lokijs');
//路径包
const path = require("path");
const { v4: uuidv4 } = require('uuid');


//定义储存路径
let fileurl = path.join(process.cwd(), "lokiFiles/userdb.json");

class UserDB {
    constructor() {
        this._ready = false;
        this.db = new loki(fileurl, {
            autoload: true,
            autoloadCallback: async () => {
                await this.initCollections();
                this._ready = true;
                if (this._resolveReady) this._resolveReady();
            },
            autosave: true,
            autosaveInterval: 5000
        });
    }

    async initCollections() {
        this.Collection = this.db.getCollection('user') ||
            this.db.addCollection('user', { unique: ['Useraccount'] });
    }

    //确保数据库初始化完成
    async ready() {
        if (this._ready) return;
        return new Promise(resolve => {
            this._resolveReady = resolve;
        });
    }

    // 添加方法
    async create(savedata) {
        await this.ready();
        //检查名称是否存在
        if ("Useraccount" in savedata) {
            if (savedata.Useraccount == "") {
                return { success: false, data: "请不要输入空用户名" };
            }
            let user = this.Collection.findOne({ Useraccount: savedata.Useraccount });
            if (!user) {
                let data = {
                    Useraccount: savedata.Useraccount,
                    Userpassword: savedata.Userpassword,
                    User_id: uuidv4(),
                    Usercreatedate: new Date().toISOString()
                }
                let result = this.Collection.insert(data);
                return { success: true, data: result }
            } else {
                return { success: false, data: "存在该用户" };
            }
        } else {
            return { success: false, data: "请传入用户名" };
        }
    }

    // 查找方法
    async find(finddata = {}, limit = 0, sort = "Usercreatedate") {
        await this.ready();
        if (Object.keys(finddata).length === 0) {
            let result;
            if (limit == 0) {
                result = this.Collection
                    .chain()
                    .find()
                    .simplesort(sort, { desc: true })
                    .data();
            } else {
                result = this.Collection
                    .chain()
                    .find()
                    .simplesort(sort, { desc: true })
                    .limit(limit)
                    .data();
            }
            return { success: true, data: result };
        } else {
            let result;
            if (limit == 0) {
                result = this.Collection
                    .chain()
                    .find(finddata)
                    .simplesort(sort, { desc: true })
                    .data();
            } else {
                result = this.Collection
                    .chain()
                    .find(finddata)
                    .simplesort(sort, { desc: true })
                    .limit(limit)
                    .data();
            }
            return { success: true, data: result };
        }
    }

    // 删除方法
    async delete(finddata = {}) {
        await this.ready();
        if ("User_id" in finddata) {
            let outcome = this.Collection.findOne(finddata);
            if (outcome) {
                let result = this.Collection.remove(outcome);
                return { success: true, data: result };
            }
            return { success: false, data: "查找不到数据" };
        } else {
            return { success: false, data: "请输入用户ID" };
        }
    }
}

module.exports = new UserDB();